(function(w) {
	// 空函数
	function shield() {
		return false;
	}
	//document.addEventListener('touchstart',shield,false);//取消浏览器的所有事件，使得active的样式在手机上正常生效
	//document.oncontextmenu=shield;//屏蔽选择函数
	// H5 plus事件处理
	var ws = null,
		as = 'pop-in';

	function plusReady() {

		ws = plus.webview.currentWebview();
		// Android处理返回键
		//		plus.key.addEventListener('backbutton', function() {
		//			back();
		//		}, false);
		compatibleAdjust();
	}
	if(w.plus) {
		plusReady();
	} else {
		document.addEventListener('plusready', plusReady, false);
	}

	//处理提示

	// DOMContentLoaded事件处理
	var domready = false;
	document.addEventListener('DOMContentLoaded', function() {
		domready = true;
		gInit();
		document.body.onselectstart = shield;
		compatibleAdjust();
	}, false);
	// 处理返回事件
	w.back = function(hide) {
		if(w.plus) {
			ws || (ws = plus.webview.currentWebview());
			if(hide || ws.preate) {
				ws.hide('auto');
			} else {
				ws.close('auto');
			}
		} else if(history.length > 1) {
			history.back();
		} else {
			w.close();
		}
	};
	// 处理点击事件
	var openw = null,
		waiting = null;
	/**
	 * 打开新窗口
	 * @param {URIString} id : 要打开页面url
	 * @param {boolean} wa : 是否显示等待框
	 * @param {boolean} ns : 是否不自动显示
	 * @param {JSON} ws : Webview窗口属性
	 */
	w.clicked = function(id, wa, ns, ws) {
		if(openw) { //避免多次打开同一个页面
			return null;
		}
		if(w.plus) {
			wa && (waiting = plus.nativeUI.showWaiting());
			ws = ws || {};
			ws.scrollIndicator || (ws.scrollIndicator = 'none');
			ws.scalable || (ws.scalable = false);
			var pre = ''; //'http://192.168.1.178:8080/h5/';
			openw = plus.webview.create(pre + id, id, ws);
			ns || openw.addEventListener('loaded', function() { //页面加载完成后才显示
				//		setTimeout(function(){//延后显示可避免低端机上动画时白屏
				openw.show(as);
				closeWaiting();
				//		},200);
			}, false);
			openw.addEventListener('close', function() { //页面关闭后可再次打开
				openw = null;
			}, false);
			return openw;
		} else {
			w.open(id);
		}
		return null;
	};
	w.openDoc = function(t, c) {
		var d = plus.webview.getWebviewById('document');
		if(d) {
			d.evalJS('updateDoc("' + t + '","' + c + '")');
		} else {
			d = plus.webview.create('/plus/doc.html', 'document', {
				zindex: 9999,
				popGesture: 'hide'
			}, {
				preate: true
			});
			d.addEventListener('loaded', function() {
				d.evalJS('updateDoc("' + t + '","' + c + '")');
			}, false);
		}
	}
	/**
	 * 关闭等待框
	 */
	w.closeWaiting = function() {
		waiting && waiting.close();
		waiting = null;
	}
	// 兼容性样式调整
	var adjust = false;

	function compatibleAdjust() {
		if(adjust || !w.plus || !domready) {
			return;
		} // iOS平台使用滚动的div
		if('iOS' == plus.os.name) {
			var t = document.getElementById("dcontent");
			t && (t.className = "sdcontent");
			t = document.getElementById("content");
			t && (t.className = "scontent");
			//iOS8横竖屏切换div不更新滚动问题
			var lasto = window.orientation;
			window.addEventListener("orientationchange", function() {
				var nowo = window.orientation;
				if(lasto != nowo && (90 == nowo || -90 == nowo)) {
					dcontent && (0 == dcontent.scrollTop) && (dcontent.scrollTop = 1);
					content && (0 == content.scrollTop) && (content.scrollTop = 1);
				}
				lasto = nowo;
			}, false);
		}
		adjust = true;
	};
	w.compatibleConfirm = function() {
		plus.nativeUI.confirm('本OS原生层面不提供该控件，需使用mui框架实现类似效果。请点击“确定”下载Hello mui示例', function(e) {
			if(0 == e.index) {
				plus.runtime.openURL("http://www.dcloud.io/hellomui/");
			}
		}, "", ["确定", "取消"]);
	}
	// 通用元素对象
	var _dout_ = null,
		_dcontent_ = null;
	w.gInit = function() {
		_dout_ = document.getElementById("output");
		_dcontent_ = document.getElementById("dcontent");
	};
	// 清空输出内容
	w.outClean = function() {
		_dout_.innerText = "";
		_dout_.scrollTop = 0; //在iOS8存在不滚动的现象
	};
	// 输出内容
	w.outSet = function(s) {
		_dout_.innerText = s + "\n";
		(0 == _dout_.scrollTop) && (_dout_.scrollTop = 1); //在iOS8存在不滚动的现象
	};
	// 输出行内容
	w.outLine = function(s) {
		_dout_.innerText += s + "\n";
		(0 == _dout_.scrollTop) && (_dout_.scrollTop = 1); //在iOS8存在不滚动的现象
	};
	// 格式化时长字符串，格式为"HH:MM:SS"
	w.timeToStr = function(ts) {
		if(isNaN(ts)) {
			return "--:--:--";
		}
		var h = parseInt(ts / 3600);
		var m = parseInt((ts % 3600) / 60);
		var s = parseInt(ts % 60);
		return(ultZeroize(h) + ":" + ultZeroize(m) + ":" + ultZeroize(s));
	};
	// 格式化日期时间字符串，格式为"YYYY-MM-DD HH:MM:SS"
	w.dateToStr = function(d) {
		return(d.getFullYear() + "-" + ultZeroize(d.getMonth() + 1) + "-" + ultZeroize(d.getDate()) + " " + ultZeroize(d.getHours()) + ":" + ultZeroize(d.getMinutes()) + ":" + ultZeroize(d.getSeconds()));
	};
	/**
	 * zeroize value with length(default is 2).
	 * @param {Object} v
	 * @param {Number} l
	 * @return {String}
	 */
	w.ultZeroize = function(v, l) {
		var z = "";
		l = l || 2;
		v = String(v);
		for(var i = 0; i < l - v.length; i++) {
			z += "0";
		}
		return z + v;
	};
})(window);

;
(function() {
	'use strict';

	/**
	 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
	 *
	 * @codingstandard ftlabs-jsv2
	 * @copyright The Financial Times Limited [All Rights Reserved]
	 * @license MIT License (see LICENSE.txt)
	 */

	/*jslint browser:true, node:true*/
	/*global define, Event, Node*/

	/**
	 * Instantiate fast-clicking listeners on the specified layer.
	 *
	 * @constructor
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	function FastClick(layer, options) {
		var oldOnClick;

		options = options || {};

		/**
		 * Whether a click is currently being tracked.
		 *
		 * @type boolean
		 */
		this.trackingClick = false;

		/**
		 * Timestamp for when click tracking started.
		 *
		 * @type number
		 */
		this.trackingClickStart = 0;

		/**
		 * The element being tracked for a click.
		 *
		 * @type EventTarget
		 */
		this.targetElement = null;

		/**
		 * X-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartX = 0;

		/**
		 * Y-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartY = 0;

		/**
		 * ID of the last touch, retrieved from Touch.identifier.
		 *
		 * @type number
		 */
		this.lastTouchIdentifier = 0;

		/**
		 * Touchmove boundary, beyond which a click will be cancelled.
		 *
		 * @type number
		 */
		this.touchBoundary = options.touchBoundary || 10;

		/**
		 * The FastClick layer.
		 *
		 * @type Element
		 */
		this.layer = layer;

		/**
		 * The minimum time between tap(touchstart and touchend) events
		 *
		 * @type number
		 */
		this.tapDelay = options.tapDelay || 200;

		/**
		 * The maximum time for a tap
		 *
		 * @type number
		 */
		this.tapTimeout = options.tapTimeout || 700;

		if(FastClick.notNeeded(layer)) {
			return;
		}

		// Some old versions of Android don't have Function.prototype.bind
		function bind(method, context) {
			return function() {
				return method.apply(context, arguments);
			};
		}

		var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
		var context = this;
		for(var i = 0, l = methods.length; i < l; i++) {
			context[methods[i]] = bind(context[methods[i]], context);
		}

		// Set up event handlers as required
		if(deviceIsAndroid) {
			layer.addEventListener('mouseover', this.onMouse, true);
			layer.addEventListener('mousedown', this.onMouse, true);
			layer.addEventListener('mouseup', this.onMouse, true);
		}

		layer.addEventListener('click', this.onClick, true);
		layer.addEventListener('touchstart', this.onTouchStart, false);
		layer.addEventListener('touchmove', this.onTouchMove, false);
		layer.addEventListener('touchend', this.onTouchEnd, false);
		layer.addEventListener('touchcancel', this.onTouchCancel, false);

		// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
		// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
		// layer when they are cancelled.
		if(!Event.prototype.stopImmediatePropagation) {
			layer.removeEventListener = function(type, callback, capture) {
				var rmv = Node.prototype.removeEventListener;
				if(type === 'click') {
					rmv.call(layer, type, callback.hijacked || callback, capture);
				} else {
					rmv.call(layer, type, callback, capture);
				}
			};

			layer.addEventListener = function(type, callback, capture) {
				var adv = Node.prototype.addEventListener;
				if(type === 'click') {
					adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
						if(!event.propagationStopped) {
							callback(event);
						}
					}), capture);
				} else {
					adv.call(layer, type, callback, capture);
				}
			};
		}

		// If a handler is already declared in the element's onclick attribute, it will be fired before
		// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
		// adding it as listener.
		if(typeof layer.onclick === 'function') {

			// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
			// - the old one won't work if passed to addEventListener directly.
			oldOnClick = layer.onclick;
			layer.addEventListener('click', function(event) {
				oldOnClick(event);
			}, false);
			layer.onclick = null;
		}
	}

	/**
	 * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
	 *
	 * @type boolean
	 */
	var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;

	/**
	 * Android requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;

	/**
	 * iOS requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;

	/**
	 * iOS 4 requires an exception for select elements.
	 *
	 * @type boolean
	 */
	var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);

	/**
	 * iOS 6.0-7.* requires the target element to be manually derived
	 *
	 * @type boolean
	 */
	var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);

	/**
	 * BlackBerry requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;

	/**
	 * Determine whether a given element requires a native click.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element needs a native click
	 */
	FastClick.prototype.needsClick = function(target) {
		switch(target.nodeName.toLowerCase()) {

			// Don't send a synthetic click to disabled inputs (issue #62)
			case 'button':
			case 'select':
			case 'textarea':
				if(target.disabled) {
					return true;
				}

				break;
			case 'input':

				// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
				if((deviceIsIOS && target.type === 'file') || target.disabled) {
					return true;
				}

				break;
			case 'label':
			case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
			case 'video':
				return true;
		}

		return(/\bneedsclick\b/).test(target.className);
	};

	/**
	 * Determine whether a given element requires a call to focus to simulate click into element.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
	 */
	FastClick.prototype.needsFocus = function(target) {
		switch(target.nodeName.toLowerCase()) {
			case 'textarea':
				return true;
			case 'select':
				return !deviceIsAndroid;
			case 'input':
				switch(target.type) {
					case 'button':
					case 'checkbox':
					case 'file':
					case 'image':
					case 'radio':
					case 'submit':
						return false;
				}

				// No point in attempting to focus disabled inputs
				return !target.disabled && !target.readOnly;
			default:
				return(/\bneedsfocus\b/).test(target.className);
		}
	};

	/**
	 * Send a click event to the specified element.
	 *
	 * @param {EventTarget|Element} targetElement
	 * @param {Event} event
	 */
	FastClick.prototype.sendClick = function(targetElement, event) {
		var clickEvent, touch;

		// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
		if(document.activeElement && document.activeElement !== targetElement) {
			document.activeElement.blur();
		}

		touch = event.changedTouches[0];

		// Synthesise a click event, with an extra attribute so it can be tracked
		clickEvent = document.createEvent('MouseEvents');
		clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
		clickEvent.forwardedTouchEvent = true;
		targetElement.dispatchEvent(clickEvent);
	};

	FastClick.prototype.determineEventType = function(targetElement) {

		//Issue #159: Android Chrome Select Box does not open with a synthetic click event
		if(deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
			return 'mousedown';
		}

		return 'click';
	};

	/**
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.focus = function(targetElement) {
		var length;

		// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
		if(deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
			length = targetElement.value.length;
			targetElement.setSelectionRange(length, length);
		} else {
			targetElement.focus();
		}
	};

	/**
	 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
	 *
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.updateScrollParent = function(targetElement) {
		var scrollParent, parentElement;

		scrollParent = targetElement.fastClickScrollParent;

		// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
		// target element was moved to another parent.
		if(!scrollParent || !scrollParent.contains(targetElement)) {
			parentElement = targetElement;
			do {
				if(parentElement.scrollHeight > parentElement.offsetHeight) {
					scrollParent = parentElement;
					targetElement.fastClickScrollParent = parentElement;
					break;
				}

				parentElement = parentElement.parentElement;
			} while (parentElement);
		}

		// Always update the scroll top tracker if possible.
		if(scrollParent) {
			scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
		}
	};

	/**
	 * @param {EventTarget} targetElement
	 * @returns {Element|EventTarget}
	 */
	FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {

		// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
		if(eventTarget.nodeType === Node.TEXT_NODE) {
			return eventTarget.parentNode;
		}

		return eventTarget;
	};

	/**
	 * On touch start, record the position and scroll offset.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchStart = function(event) {
		var targetElement, touch, selection;

		// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
		if(event.targetTouches.length > 1) {
			return true;
		}

		targetElement = this.getTargetElementFromEventTarget(event.target);
		touch = event.targetTouches[0];

		if(deviceIsIOS) {

			// Only trusted events will deselect text on iOS (issue #49)
			selection = window.getSelection();
			if(selection.rangeCount && !selection.isCollapsed) {
				return true;
			}

			if(!deviceIsIOS4) {

				// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
				// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
				// with the same identifier as the touch event that previously triggered the click that triggered the alert.
				// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
				// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
				// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
				// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
				// random integers, it's safe to to continue if the identifier is 0 here.
				if(touch.identifier && touch.identifier === this.lastTouchIdentifier) {
					event.preventDefault();
					return false;
				}

				this.lastTouchIdentifier = touch.identifier;

				// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
				// 1) the user does a fling scroll on the scrollable layer
				// 2) the user stops the fling scroll with another tap
				// then the event.target of the last 'touchend' event will be the element that was under the user's finger
				// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
				// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
				this.updateScrollParent(targetElement);
			}
		}

		this.trackingClick = true;
		this.trackingClickStart = event.timeStamp;
		this.targetElement = targetElement;

		this.touchStartX = touch.pageX;
		this.touchStartY = touch.pageY;

		// Prevent phantom clicks on fast double-tap (issue #36)
		if((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			event.preventDefault();
		}

		return true;
	};

	/**
	 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.touchHasMoved = function(event) {
		var touch = event.changedTouches[0],
			boundary = this.touchBoundary;

		if(Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
			return true;
		}

		return false;
	};

	/**
	 * Update the last position.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchMove = function(event) {
		if(!this.trackingClick) {
			return true;
		}

		// If the touch has moved, cancel the click tracking
		if(this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
			this.trackingClick = false;
			this.targetElement = null;
		}

		return true;
	};

	/**
	 * Attempt to find the labelled control for the given label element.
	 *
	 * @param {EventTarget|HTMLLabelElement} labelElement
	 * @returns {Element|null}
	 */
	FastClick.prototype.findControl = function(labelElement) {

		// Fast path for newer browsers supporting the HTML5 control attribute
		if(labelElement.control !== undefined) {
			return labelElement.control;
		}

		// All browsers under test that support touch events also support the HTML5 htmlFor attribute
		if(labelElement.htmlFor) {
			return document.getElementById(labelElement.htmlFor);
		}

		// If no for attribute exists, attempt to retrieve the first labellable descendant element
		// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
		return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
	};

	/**
	 * On touch end, determine whether to send a click event at once.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchEnd = function(event) {
		var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;

		if(!this.trackingClick) {
			return true;
		}

		// Prevent phantom clicks on fast double-tap (issue #36)
		if((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			this.cancelNextClick = true;
			return true;
		}

		if((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
			return true;
		}

		// Reset to prevent wrong click cancel on input (issue #156).
		this.cancelNextClick = false;

		this.lastClickTime = event.timeStamp;

		trackingClickStart = this.trackingClickStart;
		this.trackingClick = false;
		this.trackingClickStart = 0;

		// On some iOS devices, the targetElement supplied with the event is invalid if the layer
		// is performing a transition or scroll, and has to be re-detected manually. Note that
		// for this to function correctly, it must be called *after* the event target is checked!
		// See issue #57; also filed as rdar://13048589 .
		if(deviceIsIOSWithBadTarget) {
			touch = event.changedTouches[0];

			// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
			targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
			targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
		}

		targetTagName = targetElement.tagName.toLowerCase();
		if(targetTagName === 'label') {
			forElement = this.findControl(targetElement);
			if(forElement) {
				this.focus(targetElement);
				if(deviceIsAndroid) {
					return false;
				}

				targetElement = forElement;
			}
		} else if(this.needsFocus(targetElement)) {

			// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
			// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
			if((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
				this.targetElement = null;
				return false;
			}

			this.focus(targetElement);
			this.sendClick(targetElement, event);

			// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
			// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
			if(!deviceIsIOS || targetTagName !== 'select') {
				this.targetElement = null;
				event.preventDefault();
			}

			return false;
		}

		if(deviceIsIOS && !deviceIsIOS4) {

			// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
			// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
			scrollParent = targetElement.fastClickScrollParent;
			if(scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
				return true;
			}
		}

		// Prevent the actual click from going though - unless the target node is marked as requiring
		// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
		if(!this.needsClick(targetElement)) {
			event.preventDefault();
			this.sendClick(targetElement, event);
		}

		return false;
	};

	/**
	 * On touch cancel, stop tracking the click.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.onTouchCancel = function() {
		this.trackingClick = false;
		this.targetElement = null;
	};

	/**
	 * Determine mouse events which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onMouse = function(event) {

		// If a target element was never set (because a touch event was never fired) allow the event
		if(!this.targetElement) {
			return true;
		}

		if(event.forwardedTouchEvent) {
			return true;
		}

		// Programmatically generated events targeting a specific element should be permitted
		if(!event.cancelable) {
			return true;
		}

		// Derive and check the target element to see whether the mouse event needs to be permitted;
		// unless explicitly enabled, prevent non-touch click events from triggering actions,
		// to prevent ghost/doubleclicks.
		if(!this.needsClick(this.targetElement) || this.cancelNextClick) {

			// Prevent any user-added listeners declared on FastClick element from being fired.
			if(event.stopImmediatePropagation) {
				event.stopImmediatePropagation();
			} else {

				// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
				event.propagationStopped = true;
			}

			// Cancel the event
			event.stopPropagation();
			event.preventDefault();

			return false;
		}

		// If the mouse event is permitted, return true for the action to go through.
		return true;
	};

	/**
	 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
	 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
	 * an actual click which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onClick = function(event) {
		var permitted;

		// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
		if(this.trackingClick) {
			this.targetElement = null;
			this.trackingClick = false;
			return true;
		}

		// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
		if(event.target.type === 'submit' && event.detail === 0) {
			return true;
		}

		permitted = this.onMouse(event);

		// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
		if(!permitted) {
			this.targetElement = null;
		}

		// If clicks are permitted, return true for the action to go through.
		return permitted;
	};

	/**
	 * Remove all FastClick's event listeners.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.destroy = function() {
		var layer = this.layer;

		if(deviceIsAndroid) {
			layer.removeEventListener('mouseover', this.onMouse, true);
			layer.removeEventListener('mousedown', this.onMouse, true);
			layer.removeEventListener('mouseup', this.onMouse, true);
		}

		layer.removeEventListener('click', this.onClick, true);
		layer.removeEventListener('touchstart', this.onTouchStart, false);
		layer.removeEventListener('touchmove', this.onTouchMove, false);
		layer.removeEventListener('touchend', this.onTouchEnd, false);
		layer.removeEventListener('touchcancel', this.onTouchCancel, false);
	};

	/**
	 * Check whether FastClick is needed.
	 *
	 * @param {Element} layer The layer to listen on
	 */
	FastClick.notNeeded = function(layer) {
		var metaViewport;
		var chromeVersion;
		var blackberryVersion;
		var firefoxVersion;

		// Devices that don't support touch don't need FastClick
		if(typeof window.ontouchstart === 'undefined') {
			return true;
		}

		// Chrome version - zero for other browsers
		chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1];

		if(chromeVersion) {

			if(deviceIsAndroid) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if(metaViewport) {
					// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
					if(metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// Chrome 32 and above with width=device-width or less don't need FastClick
					if(chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}

				// Chrome desktop doesn't need FastClick (issue #15)
			} else {
				return true;
			}
		}

		if(deviceIsBlackBerry10) {
			blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);

			// BlackBerry 10.3+ does not require Fastclick library.
			// https://github.com/ftlabs/fastclick/issues/251
			if(blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if(metaViewport) {
					// user-scalable=no eliminates click delay.
					if(metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// width=device-width (or less than device-width) eliminates click delay.
					if(document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}
			}
		}

		// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
		if(layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		// Firefox version - zero for other browsers
		firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1];

		if(firefoxVersion >= 27) {
			// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896

			metaViewport = document.querySelector('meta[name=viewport]');
			if(metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
				return true;
			}
		}

		// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
		// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
		if(layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		return false;
	};

	/**
	 * Factory method for creating a FastClick object
	 *
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	FastClick.attach = function(layer, options) {
		return new FastClick(layer, options);
	};

	if(typeof define === 'function' && typeof define.amd === 'object' && define.amd) {

		// AMD. Register as an anonymous module.
		define(function() {
			return FastClick;
		});
	} else if(typeof module !== 'undefined' && module.exports) {
		module.exports = FastClick.attach;
		module.exports.FastClick = FastClick;
	} else {
		window.FastClick = FastClick;
	}

	document.addEventListener('DOMContentLoaded', function() {
		FastClick.attach(document.body);
	}, false);

}());
//--------scan-------------
var img = null;
var blist = [];

function scaned(t, r, price, remark) {
	dmpay(t, r, price, remark);
}

//数字转化为中文
function char_zh(priceNum) {
	return Arabia_to_Chinese(priceNum);

	function Arabia_to_Chinese(Num) {
		Num = Num + '';
		for(i = Num.length - 1; i >= 0; i--) {
			Num = Num.replace(",", "") //替换tomoney()中的“,”
			Num = Num.replace(" ", "") //替换tomoney()中的空格
		}
		if(isNaN(Num)) { //验证输入的字符是否为数字
			alert("请检查小写金额是否正确");
			return;
		}
		//字符处理完毕后开始转换，采用前后两部分分别转换
		part = String(Num).split(".");
		newchar = "";
		//小数点前进行转化
		for(i = part[0].length - 1; i >= 0; i--) {
			if(part[0].length > 10) {
				alert("位数过大，无法计算");
				return "";
			} //若数量超过拾亿单位，提示
			tmpnewchar = ""
			perchar = part[0].charAt(i);
			switch(perchar) {
				case "0":
					tmpnewchar = "零" + tmpnewchar;
					break;
				case "1":
					tmpnewchar = "壹" + tmpnewchar;
					break;
				case "2":
					tmpnewchar = "贰" + tmpnewchar;
					break;
				case "3":
					tmpnewchar = "叁" + tmpnewchar;
					break;
				case "4":
					tmpnewchar = "肆" + tmpnewchar;
					break;
				case "5":
					tmpnewchar = "伍" + tmpnewchar;
					break;
				case "6":
					tmpnewchar = "陆" + tmpnewchar;
					break;
				case "7":
					tmpnewchar = "柒" + tmpnewchar;
					break;
				case "8":
					tmpnewchar = "捌" + tmpnewchar;
					break;
				case "9":
					tmpnewchar = "玖" + tmpnewchar;
					break;
			}
			switch(part[0].length - i - 1) {
				case 0:
					tmpnewchar = tmpnewchar + "点";
					break;
				case 1:
					if(perchar != 0) tmpnewchar = tmpnewchar + "拾";
					break;
				case 2:
					if(perchar != 0) tmpnewchar = tmpnewchar + "佰";
					break;
				case 3:
					if(perchar != 0) tmpnewchar = tmpnewchar + "仟";
					break;
				case 4:
					tmpnewchar = tmpnewchar + "万";
					break;
				case 5:
					if(perchar != 0) tmpnewchar = tmpnewchar + "拾";
					break;
				case 6:
					if(perchar != 0) tmpnewchar = tmpnewchar + "佰";
					break;
				case 7:
					if(perchar != 0) tmpnewchar = tmpnewchar + "仟";
					break;
				case 8:
					tmpnewchar = tmpnewchar + "亿";
					break;
				case 9:
					tmpnewchar = tmpnewchar + "拾";
					break;
			}
			newchar = tmpnewchar + newchar;
		}
		//小数点之后进行转化
		if(Num.indexOf(".") != -1) {
			if(part[1].length > 2) {
				alert("小数点之后只能保留两位,系统将自动截断");
				part[1] = part[1].substr(0, 2)
			}

			for(i = 0; i < part[1].length; i++) {
				tmpnewchar = ""
				perchar = part[1].charAt(i)
				switch(perchar) {
					case "0":
						tmpnewchar = "零" + tmpnewchar;
						break;
					case "1":
						tmpnewchar = "壹" + tmpnewchar;
						break;
					case "2":
						tmpnewchar = "贰" + tmpnewchar;
						break;
					case "3":
						tmpnewchar = "叁" + tmpnewchar;
						break;
					case "4":
						tmpnewchar = "肆" + tmpnewchar;
						break;
					case "5":
						tmpnewchar = "伍" + tmpnewchar;
						break;
					case "6":
						tmpnewchar = "陆" + tmpnewchar;
						break;
					case "7":
						tmpnewchar = "柒" + tmpnewchar;
						break;
					case "8":
						tmpnewchar = "捌" + tmpnewchar;
						break;
					case "9":
						tmpnewchar = "玖" + tmpnewchar;
						break;
				}
				if(i == 0) tmpnewchar = tmpnewchar + "";
				if(i == 1) tmpnewchar = tmpnewchar + "";
				newchar = newchar + tmpnewchar;
			}
		}

		//替换所有无用汉字
		while(newchar.search("零零") != -1)
			newchar = newchar.replace("零零", "零");
		newchar = newchar.replace("零亿", "亿");
		newchar = newchar.replace("亿万", "亿");
		newchar = newchar.replace("零万", "万");
		newchar = newchar.replace("零点", "零点");
		newchar = newchar.replace("零", "零");
		newchar = newchar.replace("零", "零");
		if(newchar.charAt(newchar.length - 1) == "元" || newchar.charAt(newchar.length - 1) == "角")
			newchar = newchar;
		return newchar;
	}

	function printp(obj) {
		if(obj.style.display == "none") {
			obj.style.display = "";
		} else {
			obj.style.display = "none";
		}
	}

}


function selected(id) {
	var h = blist[id];
	update(h.type, h.result, h.file);
	if(h.result.indexOf('http://') == 0 || h.result.indexOf('http://') == 0) {
		plus.nativeUI.confirm(h.result, function(i) {
			if(i.index == 0) {
				plus.runtime.openURL(h.result);
			}
		}, '', ['打开', '取消']);
	} else {
		plus.nativeUI.alert(h.result);
	}
}


function update(t, r, f) {
	outSet('扫描成功：');
	outLine(t);
	outLine(r);
	outLine('\n图片地址：' + f);
	if(!f || f == 'null') {
		img.src = '../img/barcode.png';
	} else {
		plus.io.resolveLocalFileSystemURL(f, function(entry) {
			img.src = entry.toLocalURL();
		});
		//img.src = 'http://localhost:13131/'+f;
	}
}

function onempty() {
	if(window.plus) {
		plus.nativeUI.alert('无扫描记录');
	} else {
		alert('无扫描记录');
	}
}

function cleanHistroy() {
	if(blist.length > 0) {
		var hl = document.getElementById('history');
		hl.innerHTML = '<li id="nohistory" class="ditem" onclick="onempty();">无历史记录	</li>';
	}
	plus.io.resolveLocalFileSystemURL('_doc/barcode/', function(entry) {
		entry.removeRecursively(function() {
			// Success
		}, function(e) {
			//alert( "failed"+e.message );
		});
	});
}

/*
判断手机系统
返回:1 为安卓     0  为IOS
*/
function ismobile(test) {
	var u = navigator.userAgent,
		app = navigator.appVersion;
	if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))) {
		if(window.location.href.indexOf("?mobile") < 0) {
			try {
				if(/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)) {
					return '0';
				} else {
					return '1';
				}
			} catch(e) {}
		}
	} else if(u.indexOf('iPad') > -1) {
		return '0';
	} else {
		return '1';
	}
};

function my_toast(msg) {
	/*if(w.plus){
	    plus.nativeUI.toast(msg);
	}else{*/
	var toast = myApp.toast(msg, '', {});
	toast.show();
}

var outputStream = "";
//蓝牙连接
function Bluetooth() {}

//打印小票（原始打印方法）
/*
 *text  内容
 * sign  打印类型
 * num  
 * con_position  位置
 * */
function print(text, sign, number, con_position) {
	try {
		if(getSysInfo().search('iPhone') != -1) { //如果是苹果，则不打印
			mui.toast('未安装打印机', {
				duration: 'long',
				type: 'div'
			});
			return false;
		}
		var main = plus.android.runtimeMainActivity();
		try {
			if(getSysInfo().search("P1") != -1) {
				plus.android.invoke(main, "isBatchPrint", "true");
			}
			if(getSysInfo().search("V1") != -1) {
				plus.android.invoke(main, "V1commitPrinterBuffer");
			}
		} catch (error) {
			console.log('err');
		}

		if(sign == 1) { //打印二维码
			printQR(text, 10, 1, 10);
			return;
		} else if(sign == 8) { //打印条码
			printBarCode(text, 8, 3, 10, 2);
			return;
		}

		printText(text, 24, 3, con_position ? con_position : 0);

		try {
			if(getSysInfo().search("P1") != -1) {
				plus.android.invoke(main, "batchPrintA", "打印了所有方法");
			}
	
			if(getSysInfo().search("V1") != -1) {
				plus.android.invoke(main, "V1commitPrinterBuffer");
			}
			if(getSysInfo().search("JICAI") != -1) {
				plus.android.invoke(main, "jcPrintCommit");
			}
		} catch (error) {
			console.log('err');
		}
		
	} catch(e) {
		mui.toast('打印机连接失败', {
			duration: 'long',
			type: 'div'
		});
	}

}

/**
 * 打印二维码（原始打印）
 * @param {Object} str
 */
function QRcode(outputStream, str, codeSign) {
	//转换成字节流
	var a3 = plus.android.invoke(str, 'getBytes', 'GB18030');
	var len = eval((a3.length) + 3);
	if(len > 7092) len = 7092;
	//居中
	outputStream.write([0x1B, 0x61, 49]);
	//设置单元格大小(二维码块大小)
	if(codeSign == "code") {
		outputStream.write([0x1D, 0x28, 0x6B, 0x03, 0x00, 49, 67, 6]);
	} else {
		outputStream.write([0x1D, 0x28, 0x6B, 0x03, 0x00, 49, 67, 10]);
		//outputStream.write([GS,0x28,0x6B,0x03,0x00,0x31,0x43,10]); 
	}
	//选择二维码纠错等级
	outputStream.write([0x1D, 0x28, 0x6B, 0x03, 0x00, 49, 69, 48]);
	//outputStream.write([GS,0x28,0x6B,0x03,0x00,0x31,0x45,48]);
	//存入二维码数据
	outputStream.write([0x1D, 0x28, 0x6B, len, len >> 8, 0x31, 0x50, 0x30]);
	//循环存入数据
	for(var i = 0; i < a3.length && i < len; i++) {
		outputStream.write(a3[i]);
	} 
	//打印已存入的数据二维码
	outputStream.write([0x1D, 0x28, 0x6B, 0x03, 0x00, 49, 81, 48]);
	//换行三次
	//	outputStream.write([0x0A, 0x0A]);
}

// 打印换行（原始打印）
function aline(op, sign, text) { //48居左，49居中， 50居右
	var outputStream = bluetoothSocket.getOutputStream();
	plus.android.importClass(outputStream);
	var bytes = plus.android.invoke(text, 'getBytes', 'gbk');
	if(sign == 48) {
		//居左
		outputStream.write([0x1B, 0x61, 48]);
		outputStream.write(bytes);
		return;
	} else if(sign == 49) {
		//居中
		outputStream.write([0x1B, 0x61, 49]);
		outputStream.write(bytes);
		return;
	}
	//居右
	outputStream.write([0x1B, 0x61, 50]);
	outputStream.write(bytes);

}


function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if(month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if(strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
		" " + date.getHours() + seperator2 + date.getMinutes() +
		seperator2 + date.getSeconds();
	return currentdate;
}

// 普通支付调用扫码
function loan(type, code_id, amount, fq_num, percent) {
	plus.nativeUI.showWaiting("正在交易中，请勿退出...");
	var signx = false;
	var datas = {
		token: localStorage.getItem("token"),
		code: code_id,
		total_amount: amount,
		hb_fq_num: fq_num,
		hb_fq_seller_percent: percent
	}
	mui.ajax(weburl + model_loan, {
		data: datas,
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 50000,
		success: function(response) {
			plus.nativeUI.closeWaiting();
			if(response.status == "success") {
				var str = response.data[0].print_body;
				var reg = /\\n/g;
				str = str.replace(reg, '\n');
				printTicket(response.data[0].print_array);
//				ticket(response.data[0].store_name, str, response.data[0].out_trade_no);
				mui.closePopups();
				mui.confirm("交易成功，是否打印小票", " ", ["打印", "关闭"], function(e) {
					if(e.index == 0) {
						if(signx == false) {
							printTicket(response.data[0].print_array);
//							ticket(response.data[0].store_name, str, response.data[0].out_trade_no);
							signx = true;
							setTimeout(function() {
								signx = false;
							}, 3000);
						}
						return false;
					} else {
						mui.openWindow({
							url: "../view/detail.html",
							id: "detail.html",
							extras: {
								orderNum: response.data[0].out_trade_no,
								authNo: ""
							}
						})
					}
				}, "div")
			} else {
				mui.confirm(response.msg, " ", ["确定", "关闭"], function() {}, "div");
			}
		},
		error: function(xhr, type, errorThrown) {
			plus.nativeUI.closeWaiting();
			mui.alert("系统繁忙  请稍候重试", " ", "关闭", function() {}, "div");
		}
	});
}

//扫一扫功能
function scan(type, code_id, amount, fq_num, percent) {
	var prefix = code_id.charAt(code_id.length - 1);
	if(prefix == "-" || code_id.substring(0, 2) == "fu") { //如果是预授权的订单，则到预授权列表查询
		require(weburl + model_fundAuthLists, "json", "post", {
			token: localStorage.getItem("token"),
			type: 901,
			out_order_no: (prefix == "-") ? code_id.substring(0, (code_id.length - 1)) : code_id,
		}, function(response) {
			console.log((prefix == "-") ? code_id.substring(0, (code_id.length - 1)) : code_id);
			console.log(JSON.stringify(response));
			if(response.status == "success" && response.data) {
				mui.openWindow({
					url: "../view/depositDetail.html",
					id: "depositDetail",
					extras: {
						orderNum: response.data[0].out_order_no,
						autoNo: response.data[0].auth_no ? response.data[0].auth_no : ""
					}
				});
			} else {
				mui.alert(response.msg, " ", "关闭", function() {}, "div");
			}
			console.log(JSON.stringify(response));
		}, function() {
			mui.alert(response.msg, " ", "关闭", function() {}, "div");
		})
	} else { //否则到普通列表查询
		require(weburl + model3, "json", "post", {
			token: localStorage.getItem("token"),
			out_trade_no: code_id,
			id: "null"
		}, function(response) {
			if(response.status == 1) {
				mui.openWindow({
					url: "../view/detail.html",
					id: "detail.html",
					extras: {
						orderNum: response.data.out_trade_no
					}
				});
			} else {
				mui.alert("未查询到该订单", " ", "关闭", function() {}, "div");
			}
		}, function() {
			mui.alert("未查询到该订单", " ", "关闭", function() {}, "div");
		})
	}
}

/*
 *@ ajax请求
 * transType  请求类型get/post
 * url 请求地址
 * data:数据
 * dataType  返回的数据类型，一般为json或jsonp
 * scallback  请求成功时的函数
 * ecallback  请求失败时的函数 
 */
function require(url, dataType, transType, data, scallback, ecallback) {
	if(getSysInfo().search('V1') != -1) {
		data.mac_type = 'V1';
	} else if(getSysInfo().search('P1') != -1) {
		data.mac_type = 'P1';
		data.terminalId = localStorage.getItem('terminalId');
		data.merchantId = localStorage.getItem('merchantId');
		data.merchantName = localStorage.getItem('merchantName');
	} else if(getSysInfo().search('JICAI') != -1) {
		data.mac_type = 'JICAI';
	} else if(getSysInfo().search('iPhone') != -1) {
		data.mac_type = 'iPhone';
	} else {
		data.mac_type = getSysInfo();
	}
	data.cid = localStorage.getItem('cid');
	console.log(JSON.stringify(data));
	if(window.navigator.onLine == true) { //检测网络状态，这是为正常状态
		mui.ajax({
			type: transType,
			url: url,
			timeout: 90000,
			data: data,
			dataType: dataType,
			//			beforeSend: function(xhr) {
			//				xhr.setRequestHeader('xxx-custom-header', "kkk-123");
			//			},
			success: function(s) {
				//				console.log(JSON.stringify(s));
				//				if(s.code&&s.code == 10040) {
				//					mui.alert("token已过期，请重新登录", "提示", "确定", function() {
				//						plus.runtime.restart();
				//					}, "div");
				//					return false;
				//				}
				if(typeof(scallback) == "function") {
					scallback(s);
				}
			},
			error: function(e) {
				if(typeof(ecallback) == "function") {
					ecallback(e);
				}
			}
		});
		return false;
	}
	//如果网络异常，则弹出提示框
	mui.closePopups();
	mui.alert("网络异常，请检查您的网络", " ", "关闭", function() {}, "div");

}

//预授权押金扫码授权支付
function code(type, code_id, datas) {
	var signx = false;
	plus.nativeUI.showWaiting("用户支付中，请勿退出...");
	datas = JSON.parse(datas);
	datas.code = code_id;
	require(weburl + model_shoukuan, "json", "post", datas, function(response) {
		console.log(JSON.stringify(response));
		if(response.status == "success") {
			var str = response.data[0].print_body;
			var reg = /\\n/g;
			str = str.replace(reg, '\n');
			$(".pay_remarks").val("");
			$(".price-cash").val("0.00");
			printTicket(response.data[0].print_array);
			plus.nativeUI.closeWaiting();
//			ticket(response.data[0].store_name, str, response.data[0].out_order_no);
			mui.closePopups();
			console.log(JSON.stringify(datas));
			video("成功收款" + char_zh(datas.price) + '元');
			mui.confirm("授权成功，是否打印小票？", " ", ["打印", "关闭"], function(e) {
				if(e.index == 0) {
					if(signx == false) {
						printTicket(response.data[0].print_array);
//						ticket(response.data[0].store_name, str, response.data[0].out_order_no);
						signx = true;
						setTimeout(function() {
							signx = false;
						}, 3000);
					}
					return false;
				} else {
					mui.openWindow({
						url: "../view/depositDetail.html",
						id: "depositDetail.html",
						extras: {
							authNo: response.data[0].auth_no,
							orderNum: response.data[0].out_order_no
						}
					});
				}
			}, "div");
		} else {
			plus.nativeUI.closeWaiting();
			mui.alert(response.msg, " ", "确定", function() {}, "div");
		}
	}, function() {
		//异常处理；
		plus.nativeUI.closeWaiting();
		mui.alert("系统繁忙 请稍候重试", " ", "关闭", function() {}, "div");
	})
}

/**
 * 获取本周、本季度、本月、上月的开始日期、结束日期
 */
var now = new Date(); //当前日期
var nowDayOfWeek = now.getDay(); //今天本周的第几天
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0; //
var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastYear = lastMonthDate.getYear();
var lastMonth = lastMonthDate.getMonth();
//格式化日期：yyyy-MM-dd
function formatDate(date) {
	var myyear = date.getFullYear();
	var mymonth = date.getMonth() + 1;
	var myweekday = date.getDate();
	if(mymonth < 10) {
		mymonth = "0" + mymonth;
	}
	if(myweekday < 10) {
		myweekday = "0" + myweekday;
	}
	return(myyear + "-" + mymonth + "-" + myweekday);
}
//获得某月的天数
function getMonthDays(myMonth) {
	var monthStartDate = new Date(nowYear, myMonth, 1);
	var monthEndDate = new Date(nowYear, myMonth + 1, 1);
	var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
	return days;
}
//获得本季度的开始月份
function getQuarterStartMonth() {
	var quarterStartMonth = 0;
	if(nowMonth < 3) {
		quarterStartMonth = 0;
	}
	if(2 < nowMonth && nowMonth < 6) {
		quarterStartMonth = 3;
	}
	if(5 < nowMonth && nowMonth < 9) {
		quarterStartMonth = 6;
	}
	if(nowMonth > 8) {
		quarterStartMonth = 9;
	}
	return quarterStartMonth;
}
//获得本周的开始日期
function getWeekStartDate() {
	if(nowDayOfWeek == 0) {
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
	} else {
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
	}
	return formatDate(weekStartDate);
}
//获得本周的结束日期
function getWeekEndDate() {
	if(nowDayOfWeek == 0) {
		var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
	} else {
		var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 7);
	}
	return formatDate(weekEndDate);
}
//获得上周的开始日期
function getLastWeekStartDate() {
	var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
	return formatDate(weekStartDate);
}
//获得上周的结束日期
function getLastWeekEndDate() {
	var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
	return formatDate(weekEndDate);
}
//获得本月的开始日期
function getMonthStartDate() {
	var monthStartDate = new Date(nowYear, nowMonth, 1);
	return formatDate(monthStartDate);
}
//获得本月的结束日期
function getMonthEndDate() {
	var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
	return formatDate(monthEndDate);
}
//获得上月开始时间
function getLastMonthStartDate() {
	var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
	return formatDate(lastMonthStartDate);
}
//获得上月结束时间
function getLastMonthEndDate() {
	var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
	return formatDate(lastMonthEndDate);
}
//获得本季度的开始日期
function getQuarterStartDate() {
	var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
	return formatDate(quarterStartDate);
}
//或的本季度的结束日期
function getQuarterEndDate() {
	var quarterEndMonth = getQuarterStartMonth() + 2;
	var quarterStartDate = new Date(nowYear, quarterEndMonth,
		getMonthDays(quarterEndMonth));
	return formatDate(quarterStartDate);
}
//获取昨天的时间
function getYesterday() {
	var day1 = new Date();
	day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
	var s1 = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();
	return s1;
}

// 数字转化
function toNum(a) {
	var a = a.toString();
	//也可以这样写 var c=a.split(/\./);
	var c = a.split('.');
	var num_place = ["", "0", "00", "000", "0000"],
		r = num_place.reverse();
	for(var i = 0; i < c.length; i++) {
		var len = c[i].length;
		c[i] = r[len] + c[i];
	}
	var res = c.join('');
	return res;
}

function cpr_version(a, b) { //a为当前， b为升级
	var _a = toNum(a),
		_b = toNum(b);
	if(_a == _b) return 1;
	if(_a > _b) return 2;
	if(_a < _b) return 3;
}

/**
 * 比较版本大小，如果新版本nv大于旧版本ov则返回true，否则返回false
 * @param {String} ov
 * @param {String} nv
 * @return {Boolean} 
 */
function compareVersion(ov, nv) {
	if(!ov || !nv || ov == "" || nv == "") {
		return false;
	}
	var b = false,
		ova = ov.split(".", 4),
		nva = nv.split(".", 4);
	for(var i = 0; i < ova.length && i < nva.length; i++) {
		var so = ova[i],
			no = parseInt(so),
			sn = nva[i],
			nn = parseInt(sn);
		if(nn > no || sn.length > so.length) {
			return true;
		} else if(nn < no) {
			return false;
		}
	}
	if(nva.length > ova.length && 0 == nv.indexOf(ov)) {
		return true;
	}
}

/*
 * 打印小票，新小票格式
 * 小票共13段
 * 以数组方式返回
 *  
 * */
function printTicket(ticket_arr, sign) {

	if(getSysInfo().search('iPhone') != -1) { //如果是苹果，则不打印
		mui.toast('未安装打印机', {
			duration: 'long',
			type: 'div'
		});
		return false;
	}
	try{
		var main = plus.android.runtimeMainActivity();
	    //进入缓冲区
	    plus.android.invoke(main, "enterPrinterBuffer");
	    
	//	var ticket_arr = ['图片\n', 'Elves大酒店\n', '1号门售票厅\n', '支付方式：支付宝\n订单类型：退款\n交易时间：2018-05-17 10:23:20\n===========================\n订单号:bk201805171023201230974\n流水号:\n400521501201121212\n---------------------------\n', '业务记录：\n', '收款：￥1000 (05-23 13:02:55)\n退款：￥20 (05-23 13:02:55)\n', '退款：￥200\n', '备注：2\n===========================\n', 'bk201805171023201230974\n', '===========================\n收银员：江莱\n打印时间：2018-05-17 10:23:20\n', '天择可付    智慧收银\n', '小票凭证：0503-4\n', '交易凭证重复打印\n', ];
		//printImage(图片类型,图片位置，集财图片大小)
		printImage(replaceN(ticket_arr[0])+'', '2', '3');
		printLine(1, 1, 10);
		// printText(内容，集财字体，商米字体，居中格式)
		printText(replaceN(ticket_arr[1]), '32', '32', 1);
		printLine(1, 1, 10);
		printText(replaceN(ticket_arr[2]), '24', '24', 1);
		printLine(1, 1, 10);

		printText(replaceN(ticket_arr[3]), '24', '24', 0);
	
		printText(replaceN(ticket_arr[4]), '32', '32', 0);
	
		printText(replaceN(ticket_arr[5]), '24', '24', 0);
	
		printText(replaceN(ticket_arr[6]), '32', '32', 0);
	
		printText(replaceN(ticket_arr[7]), '24', '24', 0);
	
		//打印二维码
		printQR(replaceN(ticket_arr[8]), sign?5:8, 1, 4);

		printText(replaceN(ticket_arr[9]), '24', '24', 0);
//		printLine(3, 1, 10);
		printLine(1, 1, 10);
		printText(replaceN(ticket_arr[10]), '24', '24', 1);

		printText(replaceN(ticket_arr[11]), '24', '24', 0);
	
		printText(replaceN(ticket_arr[12]), '24', '24', 1);
	
		printLine(5, 5, 18);
	
		try {
			//开始打印
			plus.android.invoke(main, "commitPrint");
		} catch (error) {
			console.log('err');
		}

	}catch(e){
		console.log('未检测到打印机');
		mui.toast('未检测到打印机',{ duration:'long', type:'div' });
	}
}

/*
 *汇总打印
 * 
 */
function printAct(act_arr){
	console.log(act_arr);
	if(getSysInfo().search('iPhone') != -1) { //如果是苹果，则不打印
		mui.toast('未安装打印机', {
			duration: 'long',
			type: 'div'
		});
		return false;
	}
	try{
		var main = plus.android.runtimeMainActivity();
		
		//进入缓冲区
	    plus.android.invoke(main, "enterPrinterBuffer");
		
		//酒店名称
		printText(replaceN(act_arr[0]), '32', '32', 1);
		printLine(1, 1, 10);
		
		//收银员名称
		printText(replaceN(act_arr[1]), '24', '24', 1);
		printLine(1, 1, 10);
		
		//打印内容
		printText(replaceN(act_arr[2]), '24', '24', 0);

		//底部
		printText(replaceN(act_arr[3]), '24', '24', 1);
			
		//开始打印
		plus.android.invoke(main, "commitPrint");
			
	}catch(e){
		//异常处理
		console.log('未检测到打印机');
		mui.toast('未检测到打印机',{ duration:'long', type:'div' });
	}
}


/*
 *小票打印格式（原始方法）
 * head  头部
 * body  主体
 * out_order_no  订单号
 * footer  尾部
 * */
function ticket(head, body, out_order_no, footer, sign) {
	console.log(JSON.stringify(head));
	console.log(JSON.stringify(body));
	console.log(JSON.stringify(out_order_no));
	if(getSysInfo().search('iPhone') != -1) {
		console.log('进入了iphone');
		mui.toast('未安装打印机', {
			duration: 'long',
			type: 'div'
		});
		return false;
	}
	try {
		var main = plus.android.runtimeMainActivity();
	    //进入缓冲区
	  plus.android.invoke(main, "enterPrinterBuffer");
		printText(replaceN(head), '32', '32', 1);
		printLine(1, 1, 10);
		printText(replaceN(body), '24', '24', 0);
		printLine(1, 1, 10);
		console.log(out_order_no + "cs");
		printQR(replaceN(out_order_no), 5, 1, 4);
		printLine(1, 1, 10);
		printText('扫一扫订单号\n天择可付   智慧收银\n\n', '24', '24', 1);
		printLine(3, 1, 10);
		//开始打印
        plus.android.invoke(main, "commitPrint");
		return false;
	} catch(e) {
		console.log(e);
		mui.toast('打印机连接失败', {
			duration: 'long',
			type: 'div'
		});
	}
}

/*发票二维码打印格式*/
function fapiao_ticket(head, body, codeUrl, footer) {
	try {
		if(getSysInfo().search('iPhone') != -1) {
			mui.toast('未安装打印机', {
				duration: 'long',
				type: 'div'
			});
			return false;
		}
		var main = plus.android.runtimeMainActivity();

		try {
			if(getSysInfo().search("P1")!= -1){
				plus.android.invoke(main, "isBatchPrint", "true");
			}
			
			if(getSysInfo().search("V1")!= -1){
				plus.android.invoke(main,"V1enterPrinterBuffer","true");
			}
		} catch (error) {
			console.log('err');
		}

		var h=printText(head+ "\n",'24','3',1);
		
		var b=printText(body,'24','3',0);

		var num=printQR(codeUrl, 6, 3,6);
		
//		printLine(3,0,20);

		var code=printText('\n扫一扫开具电子发票\n天择可付   智慧收银\n\n','24','3',1);
		
		printLine(5,5, 20);
		
		try {
			if(getSysInfo().search("P1")!= -1){
				plus.android.invoke(main,"batchPrintA","打印了所有方法");
			}
			
			if(getSysInfo().search("V1")!= -1){
				plus.android.invoke(main,"V1commitPrinterBuffer");
		   }
			if(getSysInfo().search("JICAI") != -1) {
				plus.android.invoke(main, "jcPrintCommit");
			}
		} catch (error) {
			console.log('err');
		}
	} catch(e) {
		mui.toast('打印机连接失败', {
			duration: 'long',
			type: 'div'
		});
	}
}

/*
 * 调用银行卡SDK
 * data_json   需要传入的json数据
 * bs_code   操作参数
 */
function bs_pay(data_json, bs_code) {
	try{
		var main = plus.android.runtimeMainActivity();
		plus.android.invoke(main, "BankCarTrade", bs_code+'' , JSON.stringify(data_json));
	}catch(e){
		console.log('调用银行卡sdk失败');
		mui.toast('操作失败，请稍候再试',{ duration:'long', type:'div' });
	}
}

//打印文字
function printText(text_content, sfTextSize, jctext_size, text_position) {
	/*
	   集财打印
	 * 参数1:打印字体内容,
	 * 参数2:商米字体,
	 * 参数3:集财字体,
	 * 参数4:字体位置, (0居左, 1居中, 2居右)
	 * 参数5:是否加粗(可选)
	 */
	var main = plus.android.runtimeMainActivity();
	plus.android.invoke(main, "printText", text_content + "", sfTextSize + "", jctext_size + "", text_position + '', 'true');
}
//打印二维码
function printQR(qr_content, qr_size, qr_err_v, v1size) {
	var main = plus.android.runtimeMainActivity();
	/* 集财打印
	 * 参数1:二维码 内容 参数 
	 * 参数2: 二维码块大小(单位:点, 取值 1 至 16 ),超出设置范围默认取值10 
	 * 参数3:二维纠错等级(0:L 1:M 2:Q 3:H)
	 */
	plus.android.invoke(main, "printQrcode", qr_content + "", qr_size + "", '3', qr_size == 5 ? '0' : '1');
}

// 打印图片
function printImage(imgType, imgPosition, imgSize) {
	var main = plus.android.runtimeMainActivity();
	/* 参数1:图片类型  1 alipay   2 wx   3 bank
	 * 参数2 : 图片位置  0 1 2 中 左 右
	 */
	plus.android.invoke(main, "printBitmap", imgType + "", imgPosition + "");
}

//打印空白行
function printLine(jcline_number, sfLineNum, line_height) {
	console.log(444);
	var main = plus.android.runtimeMainActivity();
	/* 参数1:打印空白行数   jcline_number
	 * 参数2 :空白行的高度(单位：像素点) line_height
	 */
	plus.android.invoke(main, "printBlankLine", jcline_number + "", line_height + "");
}

function printBarCode(barcode_content, barcode_type, barcode_height, barcode_width, barcode_textposition) {
	var main = plus.android.runtimeMainActivity();
	/* 参数1 :条形码的内容,
	 * 参数2:条形码的格式: 0-8,
	 * 参数3:条码高度, 取值1到16, 超出范围默认取6，每个单位代表24个像素点高度, 
	 * 参数4:条码宽度, 取值1至16, 超出范围默认取12，每个单位代表24个像素点长度参数
	 * 5: 文字位置 0--不打印文字, 1--文字在条码上方, 2--文字在条码下方, 3--条码上下方均打印
	 */

	if(getSysInfo().search("JICAI") != -1) {

		plus.android.invoke(main,"jcPrintBarCode",barcode_content + "", barcode_type + "", barcode_height + "", barcode_width + "", barcode_textposition + "")
	} else if(getSysInfo().search("P1") != -1) {
		plus.android.invoke(main, "printBarcode", barcode_content + "");
	} else {
		plus.android.invoke(main, "V1BarCode", barcode_content + "", barcode_type + "", barcode_height + "", barcode_width + "", barcode_textposition);
	}
}

//监听物理返回键，1秒内连续点击两次退出应用
function muiBack() {
	var first = null;
	mui.back = function() {
		//首次按键，提示‘再按一次退出应用’
		if(!first) {
			first = new Date().getTime();
			mui.toast('再按一次退出应用');
			setTimeout(function() {
				first = null;
			}, 1000);
			console.log(1);
		} else {
			if(new Date().getTime() - first < 1000) {
				plus.runtime.quit();
			}
			console.log(2);
		}
		return false;
	};
}

// 获取设备信息
function getSysInfo() {
	Array.prototype.contains = function(needle) {
		for(i in this) {
			if(this[i].indexOf(needle) > 0)
				return i;
		}
		return -1;
	}

	var device_type = navigator.userAgent; //获取userAgent信息  
	//  document.write(device_type);//打印到页面  
	var md = new MobileDetect(device_type); //初始化mobile-detect  
	var os = md.os(); //获取系统  
	var model = "";
	if(os == "iOS") { //ios系统的处理  
		os = md.os() + md.version("iPhone");
		model = md.mobile();
	} else if(os == "AndroidOS") { //Android系统的处理  
		os = md.os() + md.version("Android");
		var sss = device_type.split(";");
		var i = sss.contains("Build/");
		if(i > -1) {
			model = sss[i].substring(0, sss[i].indexOf("Build/"));
		}
	}
	return model;
}

// WebSocket即时通讯
function notice_websokit() {
	var ws = new WebSocket("wss://pay.tiaze.com:8282");
	// 服务端主动推送消息时会触发这里的onmessage
	ws.onmessage = function(e) {
		// json数据转换成js对象
		var data = eval("(" + e.data + ")");
		var type = data.type || '';
		switch(type) {
			// Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
			case 'ping':

				// 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
				break;
			case 'login':
				$.post('{{route("WorkPost")}}', {
					'type': 'login',
					'login_type': '1',
					client_id: data.client_id,
					'user_phone': "{{auth()->guard('merchant')->user()->phone}}"
				}, function(data) {
					console.log(data)
				}, 'json');
				// 当mvc框架调用GatewayClient发消息时直接alert出来
			default:
				if(window.plus) {
					xx();
				} else {
					document.addEventListener('plusready', xx, false);
				}
		}
	};
}

// 废弃
function xx() {
	// 获取所有可视的Webview窗口
	var wvs = plus.webview.getDisplayWebview();
	for(var i = 0; i < wvs.length; i++) {
		console.log('Display webview ' + i + ': ' + wvs[i].getURL());
	}
}

// 调用音频
function payAudio(path) {
	var audio = document.createElement("audio");
	audio.src = path;
	audio.play();
}

// ---------------------------
function orderType(ordertype, data) {
	console.log(JSON.stringify(data));
	switch(ordertype) {
		case 'SMSAUTH':
			openwindow("details.html", "details.html", {
				out_order_no: data
			});
			break;
		case 'QRPAY':
			openwindow("detail.html", "detail.html", {
				orderNum: data
			});
			break;
		case 'ONLINEAUTH':
			openwindow("", "", data);
			break;
		case 'AUTH':
			openwindow("depositDetail.html", "depositDetail.html", {
				orderNum: data
			});
			break;
		case 'INVOICE':
			openwindow("", "", data);
			break;
	}
}

// 打开新窗口
function openwindow(url, id, extras) {
	mui.openWindow({
		url: url,
		id: id,
		extras: extras
	})
}

// 替换双斜杠
function replaceN(str){
	var oldStr=JSON.stringify(str);
	var reg=/\\\\/g;
	var newStr=oldStr.replace(reg,'\\');
	return JSON.parse(newStr);
}

//查询商户信息
function searchMerInfo() {
	/**
	 * 查询商户信息
	 * 
	*/
	if(getSysInfo().search("P1") != -1) {
		try{
			var main = plus.android.runtimeMainActivity();
			var merInfo = plus.android.invoke(main, "getInfoStr");
			merInfo = merInfo.split(',');
			localStorage.setItem('terminalId',merInfo[0]);
			localStorage.setItem('merchantId',merInfo[1]);
			localStorage.setItem('merchantName',merInfo[2]);
		}catch(e){
			console.log('未检验到商户号和终端号');
			mui.toast('未检验到商户号和终端号',{ duration:'long', type:'div' });
		}
	}
}

//验证字符串是否是数字
function checkNumber(theObj) {
	var reg = /^[0-9]*$/;
	if(reg.exec(theObj)) {
		return true;
	}
	return false;
}

// 播放音频
function video(info) {
	var zhText = info;
	zhText = encodeURI(zhText);
	var str = "<audio autoplay=\"autoplay\"><source src=\"http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&text=" + zhText + "\" type=\"audio/mpeg\"><embed height=\"0\" width=\"0\" src=\"http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&text=" + zhText + "\"></audio>"
	$("body").append(str);
}

// 调用摄像头接口 （暂时未用）
function scanCode() {
	var main = plus.android.runtimeMainActivity();
	plus.android.invoke(main, "scanCode", '111');
}

// 刷新
function getJavaInfo (msg) {
	plus.nativeUI.closeWaiting();
	window.history.go(-1);
//	window.location.reload();
	return false;
}